﻿using Finbuckle.MultiTenant.Abstractions;
using Finbuckle.MultiTenant.Stores.Models;
using Microsoft.EntityFrameworkCore;

namespace MultiTenant.Api.Data;

public class ApplicationDbContext(
    DbContextOptions<ApplicationDbContext> options,
    IMultiTenantContextAccessor multiTenantContextAccessor)
    : DbContext(options)
{
    private readonly ITenantInfo? _tenant = multiTenantContextAccessor.MultiTenantContext.TenantInfo;

    public DbSet<Product> Products { get; set; }
    
    protected override void OnModelCreating(ModelBuilder builder)
    {
        base.OnModelCreating(builder);
        
        // Add multi-tenant configuration to Product entity
        builder.Entity<Product>().ToTable("Products");
        builder.Entity<Product>().Property(p => p.Id).ValueGeneratedOnAdd();
        builder.Entity<Product>().Property(p => p.Name).HasMaxLength(100).IsRequired();
    }
    
    protected override void OnConfiguring(DbContextOptionsBuilder optionsBuilder)
    {
        var tenantInfo = _tenant as AppTenantInfo;
        optionsBuilder.UseSqlite(tenantInfo?.ConnectionString ?? throw new InvalidOperationException());
        base.OnConfiguring(optionsBuilder);
    }
}